package rbac.service.array;

import rbac.domain.dto.DeptDto;
import rbac.domain.entity.Dept;
import rbac.domain.vo.DeptVo;
import rbac.domain.vo.Result;
import rbac.service.IDeptService;
import rbac.service.IUserService;
import rbac.util.SingletonFactory;
import rbac.view.DeptView;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 基于数值存储的业务层-部⻔管理模块
 */

public class DeptService extends BaseService<Dept, DeptDto, DeptVo>
        implements IDeptService {

    private IUserService userService;

    private DeptService() {
        data = new Dept[DATA_SIZE + 1];
        temp = new DeptVo[DATA_SIZE];
    } // 将构造函数声明为私有
    @Override
    public Dept createEntity(DeptDto dto, int id){
        LocalDateTime now = LocalDateTime.now();
        return new Dept(id, now, now, dto.name, dto.phone);
    }

    @Override
    // 将部⻔实体对象转换为部⻔视图对象
    public DeptVo convertToVo(Dept dept){
        // 通过类名直接调⽤，⽆需创建 DeptService类的实例
        return new DeptVo(dept.getId(), dept.createAt, dept.updateAt, dept.name, dept.phone);
    }

    @Override
    public void updateEntity(DeptDto dto, Dept dept) {
        dept.updateAt = LocalDateTime.now();
        dept.name = dto.name; // 原来在实体类的数据 -->-替换-> 刚刚输入在dto类的数据
        dept.phone = dto.phone;
    }

    @Override
    public Result delete(int id){
        if (!existsById(id)){
            return Result.failure("删除失败，不存在该数据");
        }

        if (userService == null) { //懒加载
            userService = SingletonFactory.getInstance(UserService.class);
        }
        if (userService.deptInUse(id)) {
            return Result.failure("删除失败，有⽤户属于该部⻔，不能删除");
        }

        // 将指定ID的部⻔数据置为 null，表示删除该数据
        data[id] = null;

        return Result.success("删除成功", null);
    }

}

